var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');//功能：在控制台中，显示req请求的信息
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require("express-session");
var flash  = require("connect-flash");
var routes = require('./routes/index');
var admin = require('./routes/admin');
var multer = require("multer");//功能：文件上传

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(flash());

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(require('less-middleware')(path.join(__dirname, 'public'),
    {
        force: true,
        once: true,
        preprocess: {
            path: function (pathname, req) {
                return pathname.replace('\/css', '\/less');
            }
        }
    }));
app.use(express.static(path.join(__dirname, 'public')));

app.use(cookieParser());
app.use(session({
    //genid: function(req) {
    //    //return genuuid(); // use UUIDs for session IDs
    //    return null;
    //},
    secret: 'keyboard cat',
    //name: 'testapp',   //这里的name值得是cookie的name，默认cookie的name是：connect.sid
    cookie: {maxAge: 900000 },//设置maxAge是80000ms，即80s后session和相应的cookie失效过期
    resave: false,
    //saveUninitialized: true
}));

app.use(multer({
    dest: './public/upload',
    rename: function(fieldname,filename){
        //console.log("fieldname:"+fieldname);//input name
        //console.log("filename:"+filename); //field name
        return filename;
    }
}));

 //routes(app);
app.use('/', routes);
app.use('/admin', admin);

var admin_hotel = require('./routes/admin/hotel');
var admin_users = require('./routes/admin/users');
var admin_book = require('./routes/admin/book');
app.use('/admin/', [admin_hotel,admin_users,admin_book]);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
